/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.generator.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.generator.entity.BsnMentorEntity;
import io.renren.modules.generator.service.BsnMentorService;
import io.renren.modules.oss.cloud.LocalStorageService;
import io.renren.modules.oss.cloud.LocalStorageService.SavedFileInfo;
import io.renren.modules.oss.entity.SysOssEntity;
import io.renren.modules.oss.service.SysOssService;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件上传保存在本地
 * 
 */
@RestController
@RequestMapping("generator/lss")
public class LocalSSController {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private LocalStorageService localStorageService;

	@Autowired
	private SysOssService sysOssService;
	
	@Autowired
	private BsnMentorService bsnMentorService;
	/**
	 * 上传文件
	 */
	@Login
	@PostMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		
		//objectType={mentor;parent;manager} 后两个类型目前没有
		String objectType = params.get("objectType").toString();
		//busType={lvli;touxiang}
		String busType = params.get("busType").toString();
		String configKey;
		if (busType.equals("lvli")) {
			configKey = "lvLiSavePath";
		} else {
			configKey = "touXiangSavePath";
		}
		//附件关联的业务表单对象ID
		String formId = params.get("formId").toString();
		SavedFileInfo savedInfo = localStorageService.saveFile(file, configKey);
				
		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setId(savedInfo.key);
		ossEntity.setUrl(savedInfo.fullPath);
		ossEntity.setShortName(file.getOriginalFilename());
		ossEntity.setStorageType(busType);
		ossEntity.setCreateDate(new Date());
		sysOssService.insert(ossEntity);
		saveTargetEntity(formId, objectType, savedInfo.key + "-" + ossEntity.getShortName());
		
		return R.ok().put("url", ossEntity.getUrl());
	}
	
	@Login
	@RequestMapping("/download/{fileId}")
	@ResponseBody
	public R download(@PathVariable("fileId") String fileId, HttpServletResponse response) {
		if (StringUtils.isBlank(fileId)) {
			return R.error("参数 fileId 不能为空");
		}
		fileId = fileId.split("-")[0];
		SysOssEntity ossEntity = sysOssService.selectById(fileId);
		File file = new File(ossEntity.getUrl());
		if (!file.exists()) {
			logger.error("文件不存在，fileID={}，url={}", fileId, ossEntity.getUrl());
			return R.error("附件：" + fileId + "不存在");
		}
	
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
		InputStream in = null;
		try {
			in = FileUtils.openInputStream(file);
			OutputStream out = response.getOutputStream();
			IOUtils.copy(in, out);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			return R.error("读取附件：" + fileId + "失败");
		} finally {
			try {
				in.close();
			} catch (IOException e) {
			}
		}
		return null;
		
	}

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") String id){
    	SysOssEntity ossEntity = sysOssService.selectById(id);    	
        return R.ok().put("shortName", ossEntity.getShortName());
    }

	/**
	 * 删除
	 */
	@PostMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.deleteBatchIds(Arrays.asList(ids));

		return R.ok();
	}

	private void saveTargetEntity(String entityId, String entityType, String fileId) {
		if (entityType.equals("mentor")) {
			BsnMentorEntity one = bsnMentorService.selectById(entityId);
			one.setJianliurl(fileId);
			bsnMentorService.updateById(one);
		}
	}
}
